<script setup lang="ts">
import { applyInvoice, getCompanyBillInfoList } from "~/api/user";

const props = defineProps({
  openActive: {
    type: Object,
    default: () => {},
  },
});

const formData = ref({
  companyName: "",
  email: "",
  invoiceAmount: 0,
  invoiceId: 0,
  invoiceType: 1, // 默认普票
  taxNumber: "",
  telephone: "",
});

// 选中的发票抬头ID
const selectedBillId = ref(null);

const emits = defineEmits(["close"]);
const close = (type=null) => {
  emits("close", type);
};

const rules = ref({
  companyName: [{ required: true, message: "发票抬头不能为空", trigger: "blur,change" }],
  email: [
    { required: true, message: "接收邮箱不能为空", trigger: "blur,change" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
          callback(new Error("请输入正确的邮箱格式"));
        } else {
          callback();
        }
      },
      trigger: "blur,change",
    },
  ],
  telephone: [{ required: true, message: "电话不能为空", trigger: "blur,change" }],
  taxNumber: [{ required: true, message: "税号不能为空", trigger: "blur,change" }],
});

const invoiceTypeOptions = ref([
  { value: 1, label: "普票" },
  { value: 2, label: "专票" },
  { value: 3, label: "个人" },
]);

const formRef = ref(null);
const open = async () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 验证是否选择了发票抬头
      if (!selectedBillId.value) {
        return ElMessage.warning("请选择发票抬头");
      }
      
      // 只提交这4个参数
      const submitData = {
        orderSn: props.openActive.orderSn || "",
        billId: selectedBillId.value,
        invoiceAmount: props.openActive.amount || 0,
        invoiceType: formData.value.invoiceType,
      };
      
      try {
        const data = await applyInvoice(submitData);
        if (data.code === 200) {
          ElMessage.success("发票申请成功");
          close("add");
        }
      } catch (e) {
        // 处理错误
      }
    }
  });
};

const billList = ref([]);
// 获取发票抬头列表
const getBillList = async () => {
  try {
    const result = await getCompanyBillInfoList();
    
    // 如果返回的是数组，直接使用；如果是对象包含 records，使用 records
    let list = [];
    if (Array.isArray(result.data)) {
      list = result.data;
    } else if (result.data && typeof result.data === 'object') {
      list = result.data.records || result.data.list || [];
    }
    
    if (list && list.length > 0) {
      billList.value = list.map((item: any) => {
        return {
          label: item.companyName,
          value: item.id,
          ...item,
        };
      });
    } else {
      billList.value = [];
    }
  } catch (e) {
    ElMessage.error('获取发票抬头列表失败，请重试');
  }
};

// 初始化表单数据
const initFormData = () => {
  if (props.openActive && props.openActive.id) {
    // 初始化发票金额
    formData.value.invoiceAmount = props.openActive.amount || 0;
    // 重置表单
    formData.value.companyName = "";
    formData.value.email = "";
    formData.value.invoiceId = 0;
    formData.value.invoiceType = 1;
    formData.value.taxNumber = "";
    formData.value.telephone = "";
    selectedBillId.value = null;
  }
};

// 组件挂载时获取发票抬头列表（由于使用了 v-if，每次弹窗打开都会重新创建组件）
onMounted(async () => {
  // 先初始化表单数据
  initFormData();
  // 立即获取发票抬头列表
  await getBillList();
});

// 监听 openActive 变化（作为备用，确保数据同步）
watch(() => props.openActive?.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    initFormData();
    // 如果列表为空，重新获取
    if (billList.value.length === 0) {
      getBillList();
    }
  }
}, { immediate: false });

const headChange = (billId) => {
  const find = billList.value.find((item) => item.id === billId);
  if (find) {
    formData.value.companyName = find.companyName;
    formData.value.taxNumber = find.taxNumber;
    formData.value.telephone = find.telephone || "";
    formData.value.email = find.email || "";
  } else {
    // 如果找不到（清空选择），清空相关字段
    formData.value.companyName = "";
    formData.value.taxNumber = "";
    formData.value.telephone = "";
    formData.value.email = "";
  }
};
</script>

<template>
  <div class="dialog" @click="close">
    <div class="dialog-box" @click.stop>
      <div class="header">
        <div class="left">
          <img src="~/assets/dialog-icon.png" alt="" />
          <span>开具发票</span>
        </div>
        <img class="close" src="~/assets/modal-close.png" alt="" @click="close" />
      </div>
      <div class="dialog-content">
        <el-form ref="formRef" :model="formData" label-position="top" :rules="rules">
          <el-form-item label="开票金额" required>
            <el-input
              :value="props.openActive.amount"
              placeholder="请输入开票金额"
              disabled
              style="height: 40px"
            />
          </el-form-item>
          <el-form-item label="发票类型" required prop="invoiceType">
            <el-select
              v-model="formData.invoiceType"
              placeholder="请选择发票类型"
              style="width: 100%"
            >
              <el-option
                v-for="item of invoiceTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发票抬头" required prop="companyName">
            <el-select
              v-model="selectedBillId"
              placeholder="请选择发票抬头"
              @change="headChange"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item of billList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="税号" required prop="taxNumber">
            <el-input
              v-model="formData.taxNumber"
              placeholder="请输入税号"
              style="height: 40px"
            />
          </el-form-item>
          <el-form-item label="电话" required prop="telephone">
            <el-input
              v-model="formData.telephone"
              placeholder="请输入电话"
              style="height: 40px"
            />
          </el-form-item>
          <el-form-item label="接收邮箱" required prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入发票接收邮箱"
              style="height: 40px"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="footer">
        <span class="btn" @click="close">取消</span>
        <span class="btn" @click="open">开票</span>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.dialog {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(25, 30, 40, 0.4);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-box {
  width: 400px;
  background: #ffffff;
  border-radius: 12px 12px 12px 12px;
  padding: 24px;

  .header {
    display: flex;
    align-items: center;
    padding-bottom: 20px;

    .left {
      flex: 1;
      display: flex;
      align-items: center;

      img {
        width: 20px;
        height: 20px;
        margin-right: 4px;
      }

      span {
        font-size: 16px;
        color: #191e28;
        font-weight: bold;
      }
    }

    .close {
      width: 18px;
      height: 18px;
      cursor: pointer;
    }
  }
  .footer {
    display: flex;
    padding: 32px 0 0;
    justify-content: flex-end;
    span {
      width: 92px;
      height: 36px;
      cursor: pointer;
    }
    .btn:nth-child(1) {
      background: #ffffff;
      border-radius: 8px 8px 8px 8px;
      border: 1px solid rgba(25, 30, 40, 0.08);
      display: flex;
      align-items: center;
      justify-content: center;
      color: rgba(25, 30, 40, 0.6);
      margin-right: 12px;
    }
    .btn:nth-child(2) {
      background: #1dbf73;
      border-radius: 8px 8px 8px 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
    }
    .btn.red {
      background: none;
      color: #ff4f4f;
      border: 1px solid #ff4f4f;
    }
  }
  .dialog-content p {
    display: flex;
  }
  .textarea {
    margin-top: 10px;
    textarea {
      width: 100%;
      height: 96px;
      background: rgba(25, 30, 40, 0.02);
      border-radius: 12px 12px 12px 12px;
      border: 1px solid rgba(25, 30, 40, 0.08);
      padding: 16px;
      box-sizing: border-box;
      resize: none;
    }
  }
}
</style>

<style>
.dialog .el-select__wrapper {
  height: 40px;
}
.dialog .el-form--default.el-form--label-top .el-form-item .el-form-item__label {
  color: #191e28;
  font-weight: bold;
}
</style>
